package com.warom.sdg.webview.jsinterface;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.webkit.JavascriptInterface;

import com.google.gson.Gson;
import com.warom.sdg.config.MeasurementPoint;
import com.warom.sdg.config.PlcMeasurementConfig;
import com.warom.sdg.enums.ModuleType;
import com.warom.sdg.webview.BaseWebViewJsInterface;
import com.warom.sdg.webview.WebViewWrapper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Consumer;

/**
 * 能耗监测专用WebViewJsInterface
 * 提供能耗监测页面所需的JavaScript接口
 */
public class WebViewJsPowerMonitoringInterface extends BaseWebViewJsInterface {
    private static final String TAG = "PowerMonitoringJsInterface";
    private final Handler mHandler = new Handler(Looper.getMainLooper());
    private final Gson gson = new Gson();
    private final ExecutorService executor = Executors.newSingleThreadExecutor();

    private WebViewWrapper webViewWrapper;

    /**
     * 构造函数
     * @param context 上下文
     */
    public WebViewJsPowerMonitoringInterface(Context context) {
        super(context, null);
    }

    /**
     * 构造函数
     * @param context 上下文
     * @param webViewWrapper WebView包装器
     */
    public WebViewJsPowerMonitoringInterface(Context context, WebViewWrapper webViewWrapper) {
        super(context,webViewWrapper);
        this.webViewWrapper = webViewWrapper;
    }

   

    /**
     * 异步获取能耗数据
     * @param args 参数
     * @param requestId 请求ID
     */
    @JavascriptInterface
    public void getPowerMonitoringDataAsync(String args, String requestId) {
        executor.execute(() -> getPowerMonitoringData(args, result -> handleAsyncResponse(requestId, result)));
    }

    //实际业务处理
    private void getPowerMonitoringData(String argsJson, Consumer<String> callback) {
        try {
            // 获取电力监测模块对应的设备-测点映射
            Map<com.warom.sdg.model.DeviceType, List<MeasurementPoint>> powerMonitoringMap =
                PlcMeasurementConfig.moduleDevicePointsMap.get(ModuleType.POWER_MONITORING);
            
            // 如果映射为空，返回空列表
            if (powerMonitoringMap == null || powerMonitoringMap.isEmpty()) {
                callback.accept(gson.toJson(new ArrayList<>()));
                return;
            }
            
            // 收集所有设备的测点到一个列表
            List<MeasurementPoint> allPoints = new ArrayList<>();
            for (List<MeasurementPoint> devicePoints : powerMonitoringMap.values()) {
                if (devicePoints != null && !devicePoints.isEmpty()) {
                    allPoints.addAll(devicePoints);
                }
            }
            
            // 返回所有测点的JSON
            callback.accept(gson.toJson(allPoints));
        } catch (Exception e) {
            Log.e(TAG, "获取电力监测数据失败", e);
            callback.accept("[]");
        }
    }






    

}
   